<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/excel')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table :data="list" border :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="用户图片" width="100">
            <template #default="{row}">
              <img v-imgerror="require('@/assets/common/bigUserHeader.png')" :src="row.staffPhoto" style="width:100%" @click="showCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <!-- 使用作用域插槽自定义数据展示内容 -->
            <template #default="{row}">
              {{ formatData(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :current-page="pagesize.page"
            :page-size="pagesize.size"
            :total="total"
            @current-change="handleCurrentChange"
          />
          <!-- <el-pagination
            :current-page="currentPage4"
            :page-sizes="[100, 200, 300, 400]"
            :page-size="100"
            layout="total, sizes, prev, pager, next, jumper"
            :total="400"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          /> -->
        </el-row>
      </el-card>
      <el-dialog title="添加" :visible.sync="showDialog">
        <addEmployees v-if="showDialog" @close="showDialog = false" @success="success" />
      </el-dialog>
      <el-dialog title="生成二维码" :visible.sync="showRow">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <el-dialog title="分配角色" :visible.sync="showAssignRole">
        <assignRole :cur-id="curId" @success="showAssignRole = false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getEmployees, delEmployees } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import addEmployees from './empDialog.vue'
import assignRole from './assignRole.vue'

// const hireType = {} // {1：正式，2：非正式}
// EmployeeEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })

const hireType = EmployeeEnum.hireType.reduce((sum, item) => {
  sum[item.id] = item.value
  return sum
}, {})

import Qrcode from 'qrcode'
export default {
  components: {
    addEmployees,
    assignRole
  },
  data() {
    return {
      curId: '',
      showAssignRole: false, // 控制分配角色弹层
      showRow: false,
      showDialog: false, // 控制弹层显示隐藏
      list: [], // 储存渲染列表数据
      total: 0, // 总条数
      pagesize: { // 发送请求需要的数据
        page: 1,
        size: 5
      }
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    hAssignRole(id) {
      this.showAssignRole = true
      this.curId = id
    },
    showCode(url) {
      if (url) {
        this.showRow = true
        this.$nextTick(() => {
          const canvas = this.$refs.myCanvas
          Qrcode.toCanvas(canvas, url)
        })
      }
    },
    // 导出英文转中文
    exportExcel() {
      const { tHeader, data } = this.tranZhkeyToExcel(this.list)
      // import('@/vendor/Export2Excel')  懒加载的方式导入一个模块， 返回值是一个promise实例
      import('@/vendor/Export2Excel').then(excel => {
        // excel指的模块对象，那么就可以使用这个模块对象去调用这个模块里面的函数或者访问变量   excel.函数名()

        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // console.log(list, 'listaaaaaaaaaaaaaaaaaaaa')
        // const data = this.formatJson(filterVal, list)
        // console.log(data, 'dataaaaaaaaaaaaaaaaa') // [[1,'三体','刘慈欣',100000,'2022-11-05'],[2,'西游记','吴承恩',100000,'1995-11-05']]
        // const data = [[1, '三体', '刘慈欣', 100000, '2022-11-05'], [2, '西游记', '吴承恩', 100000, '1995-11-05']]
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    // 导出英文转中文
    tranZhkeyToExcel(list) {
      //    中引文的映射对象
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 生成表头
      const one = list[0]
      if (!one) return
      const tHeader = Object.keys(one).map(enkey => {
        return mapInfo[enkey]
      })
      const data = list.map(item => {
        return Object.values(item)
      })
      // console.log('data', data)
      return { tHeader, data }
    },
    success() {
      this.total++
      const maxpage = Math.ceil(this.total / this.pagesize.size)
      this.pagesize.page = maxpage
      // 重新渲染页面
      this.loadEmployees()
      // 关闭弹层
      this.showDialog = false
    },
    // 聘用形式枚举
    formatData(num) {
      return hireType[num] || '未知'
    },
    // 获取员工列表
    async loadEmployees() {
      try {
        const res = await getEmployees(this.pagesize)
        console.log(res)
        // 提示用户
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 给渲染数据赋值
        this.list = res.data.rows
        // 给总条数赋值
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    },
    // 分页
    handleCurrentChange(val) {
      this.pagesize.page = val
      this.loadEmployees()
    },
    // 删除功能
    hDel(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployees(id)
        // console.log(res)
        if (res.code === 10000) {
          this.$message.success(res.message)
          if (this.list.length === 1) {
            this.pagesize.page--
            if (this.pagesize.page <= 0) {
              this.pagesize.page = 1
            }
          }
          // 从新渲染数据
          this.loadEmployees()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除11'
        })
      })
    }
  }
}
</script>
